package com.faf.ui;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.faf.bean.Food;
import com.faf.dao.impl.FoodDaoImpl;
import com.faf.tools.DbUtils;

/**
 * Servlet implementation class Index
 */
@WebServlet("/Index")
public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Index() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8"); 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		FoodDaoImpl daoFood = new FoodDaoImpl();
		
		HashMap<String, ArrayList<Food>> hash_type2food = new HashMap<String, ArrayList<Food>>();
		
		try {
			HashSet<String> foodTypes = daoFood.getFoodTypes();			
			for(String type : foodTypes) {
				ArrayList<Food> foodList = daoFood.getFoodByType(type);
				ArrayList<Food> _foodList = new ArrayList<Food>();
				for(int iCount = 0;iCount < 4;iCount ++) {
					if(iCount + 1 > foodList.size())
						continue;
					_foodList.add(foodList.get(iCount));
				}
				hash_type2food.put(type, _foodList);
			}
			
			DbUtils.getConnection().close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		request.setAttribute("index_dat_over", true);
		request.setAttribute("index_dat_foodmap", hash_type2food);
		request.getRequestDispatcher("/UserGlobal/index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
